//
//  CPFileUtil.swift
//  BabaLink
//
//  Created by wrs on 2018/8/10.
//  Copyright © 2018年 wrs. All rights reserved.
//

import Foundation

public func createDirectory(dirPath: String) -> Bool {
    var isDirectory = ObjCBool.init(false);
    if !FileManager.default.fileExists(atPath: dirPath, isDirectory: &isDirectory) { //如果不存在则创建目录
        do {
            try FileManager.default.createDirectory(atPath: dirPath, withIntermediateDirectories: true, attributes: nil)
            return true
        } catch {
           return false
        }
    }
    if !isDirectory.boolValue { //存在但不是目录
        return false
    }
    return true
}

public func getExtOfFile(filePath: String) -> String {
    let fileName = getItemNameAtPath(path: filePath)
    let fileString = NSString(string: fileName)
    let range =  fileString.range(of: ".", options: NSString.CompareOptions.backwards)
    if range.location != NSNotFound {
         return fileString.substring(from: range.location + 1)
    }
    return ""
}

public func getItemNameAtPath(path: String) -> String {
    var str = path
    if path.hasSuffix("/") {
        str = String(path.suffix(path.count - 1))
    }
    let string: NSString = NSString(string: str)
    let range = string.range(of: "/", options: NSString.CompareOptions.backwards)
    if range.location != NSNotFound {
       return string.substring(from: range.location + 1)
    }
    return path
}

public func getBundleFileContentString(resource: String, type: String) -> String? {
    let path = Bundle.main.path(forResource: resource, ofType: type)
    if let tempPath = path {
        if let str = try? String(contentsOfFile: tempPath) {
            return str
        } else {
            return nil
        }
    } else {
        return nil
    }
}

public func getBundleFileContentDictionary(resource: String, type: String) -> Any? {
    let path = Bundle.main.path(forResource: resource, ofType: type)
    do {
        let url = URL(fileURLWithPath: path!)
        let data = try Data(contentsOf: url)
        let jsonData:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
        return jsonData;
    } catch  {
        return nil
    }
}

public func deleteFile(filePath: String) -> Bool {
    if FileManager.default.fileExists(atPath: filePath) {
        do {
            try  FileManager.default.removeItem(atPath: filePath)
            return true
        } catch  {
            return false
        }
       
    }
    return true
}
